package com.sxkj.web.controller.sys;

import com.sxkj.entity.entity.sys.Menu;
import com.sxkj.entity.entity.sys.User;
import com.sxkj.common.response.ResponseResult;
import com.sxkj.service.redis.RedisService;
import com.sxkj.service.sys.MenuService;
import com.sxkj.service.sys.UserRoleService;
import com.sxkj.service.sys.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @title: UserController
 * @author: daixiaowei
 * @date: 2019年12月09日 16:56
 * @description: User APi
 */
@Controller
@Api(tags = "UserController", description = "后台用户管理")
@RequestMapping("/admin")
public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private MenuService menuService;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     *
     * @title: register
     * @author: daixiaowei
     * @date: 2019年12月09日 下午 05:00:34
     * @description: 新用户注册
     * @param: sysUser
     * @return:
     */
    @ApiOperation(value = "用户注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult register(@RequestBody User sysUser, BindingResult result) {
        User umsAdmin = userService.register(sysUser);
        if (umsAdmin == null) {
            ResponseResult.failure("1");
        }
        return ResponseResult.success(umsAdmin);
    }

    /**
     *
     * @title: login
     * @author: daixiaowei
     * @date: 2019年12月09日 下午 05:00:18
     * @description: 登录验证并返回token和权限
     * @param: userLoginParam
     * @return:
     */
    @ApiOperation(value = "登录以后返回token")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult login(@RequestBody User user,
                                BindingResult result, HttpServletRequest request, HttpServletResponse response) {
        return userService.login(user, request, response);
    }

    /**
     *
     * @title: logout
     * @author: daixiaowei
     * @date: 2019年12月23日 上午 10:35:55
     * @description: 登出功能
     * @param:
     * @return:
     */
    @ApiOperation(value = "登出功能")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult logout() {
        return ResponseResult.success();
    }

    /**
     *
     * @title: getPermissionList
     * @author: daixiaowei
     * @date: 2019年12月10日 下午 01:47:02
     * @description: 查询权限接口(待优化)
     * @param: userId
     * @return:
     */
    @ApiOperation("获取用户权限")
    @RequestMapping(value = "/permission/{userId}", method = RequestMethod.GET)
    @ResponseBody
    @PreAuthorize("hasAuthority('read')")
    public ResponseResult getPermissionList(@PathVariable String userId) {
        List<Menu> permissionList = menuService.getPermissionList(userId);
        return ResponseResult.success(permissionList);
    }

    /**
     *
     * @title: refreshToken
     * @author: daixiaowei
     * @date: 2019年12月13日 上午 09:44:04
     * @description: 主动刷新token(后期移植微信或支付宝等可以调用)
     * @param: request
     * @return:
     */
    @ApiOperation(value = "刷新token")
    @RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = userService.refreshToken(token);
        if (refreshToken == null) {
            return ResponseResult.failure("token已经过期！");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return ResponseResult.success(tokenMap);
    }

    /**
     *
     * @title: searchUserListPage
     * @author: daixiaowei
     * @date: 2019年12月19日 上午 11:45:51
     * @description: 查询用户列表
     * @param: nickname pageSize pageNum
     * @return:
     */
    @ApiOperation(value = "查询用户列表")
    @RequestMapping(value = "/searchUserListPage", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult searchUserListPage(@RequestParam(value =
            "nickName") String nickName, @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                                               @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        return  ResponseResult.success(userService.searchListPage(nickName,pageSize,pageNum));
    }

    /**
     *
     * @title: checkUserUnique
     * @author: daixiaowei
     * @date: 2019年12月19日 下午 02:40:18
     * @description: 检查登录名是否重复
     * @param: userName
     * @return:
     */
    @ApiOperation(value = "检查登录名是否重复")
    @RequestMapping(value = "/checkUserUnique", method = RequestMethod.GET)
    @ResponseBody
    public Boolean checkUserUnique(@RequestParam(value =
            "userName") String userName) {
        return userService.searchUniqueByName(userName);
    }

    /**
     *
     * @title: userAdd
     * @author: daixiaowei
     * @date: 2019年12月19日 下午 05:41:20
     * @description: 用户添加
     * @param: user
     * @return:
     */
    @ApiOperation(value = "用户添加")
    @RequestMapping(value = "/userAdd", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult userAdd(@RequestBody User user, BindingResult result) {
        User umsAdmin = userService.userAdd(user);
        if (umsAdmin == null) {
            ResponseResult.failure("用户添加失败");
        }
        return ResponseResult.success();
    }

    /**
     *
     * @title: userEdit
     * @author: daixiaowei
     * @date: 2019年12月20日 上午 10:46:57
     * @description: 用户修改
     * @param: user
     * @return:
     */
    @ApiOperation(value = "用户修改")
    @RequestMapping(value = "/userEdit", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult userEdit(@RequestBody User user, BindingResult result) {
        User umsAdmin = userService.userUpdate(user);
        if (umsAdmin == null) {
            ResponseResult.failure("用户修改失败");
        }
        return ResponseResult.success(umsAdmin);
    }


    /**
     *
     * @title: userDelete
     * @author: daixiaowei
     * @date: 2019年12月20日 下午 01:41:14
     * @description: 删除
     * @param: map
     * @return:
     */
    @ApiOperation(value = "用户删除")
    @RequestMapping(value = "/userDelete", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult userDelete(@RequestBody Map map, BindingResult result) {
        userService.deleteByUserId(map.get("id").toString());
        return ResponseResult.success();
    }

    /**
     *
     * @title: restPassword
     * @author: daixiaowei
     * @date: 2019年12月20日 下午 01:46:31
     * @description: 重置密码
     * @param: map
     * @return:
     */
    @ApiOperation(value = "重置密码")
    @RequestMapping(value = "/restPassword", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult restPassword(@RequestBody Map map, BindingResult result) {
        userService.restPassword(map.get("id").toString());
        return ResponseResult.success();
    }


    /**
     *
     * @title: searchUserRole
     * @author: daixiaowei
     * @date: 2019年12月21日 下午 04:31:38
     * @description: 通过userId查询出UserRole
     * @param: userId
     * @return:
     */
    @ApiOperation(value = "查询userRole")
    @RequestMapping(value = "/searchUserRole", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult searchUserRole(@RequestParam(value =
            "userId") String userId) {
        return  ResponseResult.success(userRoleService.searchUserRoleByRoleId(userId));
    }


}
